import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Popconfirm } from 'antd';
import { ProColumns, ActionType, EditableProTable } from '@ant-design/pro-table';
import OptForm from './OptForm';
import TableHint from '@/components/TableHint/Index';
import { 
  getNavbarList, 
  postNavbar, 
  deleteNavbar,
  adjustNavSort
} from '@/services/mall/api';
import { MsgType, replaceImgHost, showMsg } from '@/utils/utils';
import { PlusOutlined, SortDescendingOutlined } from '@ant-design/icons';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import { OptType } from '@/utils/constants';

const Index: React.FC = () => {
  const [visible, setVisible] = useState(false)
  const [currentRow, setCurrentRow] = useState({});
  const [navbarList, setNavbarList] = useState<MALLAPI.NavbarItem[]>([]);
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const actionRef = useRef<ActionType>();
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  const [deleteLoading, setDeleteLoading] = useState<boolean>(false);
  const [line, setLine] = useState<number>(-1);
  const columns: ProColumns<MALLAPI.NavbarItem>[] = [
    {
      title: '栏位名称',
      align: 'center',
      dataIndex: 'navbar_name',
      editable: false
    },
    {
      title: '栏位图标',
      align: 'center',
      dataIndex: 'navbar_url',
      valueType: 'image',
      editable: false,
      fieldProps: {
        style: {
          width: '50px',
          // height: '40px'
        },
        preview: false
      }
    },
    {
      title: '栏位排序',
      align: 'center',
      dataIndex: 'sort',
      valueType: 'digit'
    },
    {
      title: '栏位下商品数量',
      align: 'center',
      dataIndex: 'goods_num',
      editable: false
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, record, index) => {
        return [
          <PermissionControl key="edit" action_id="500501003">
            <a onClick={() => {
              setVisible(true);
              setCurrentRow(record);
              setOptType(OptType.VIEW);
            }}>查看</a>
          </PermissionControl>,
          <PermissionControl key="delete" action_id="500501005">
            <Popconfirm
              placement="topRight"
              title='删除后此栏位将不在商城展示，是否继续？'
              onConfirm={async () => {
                if (deleteLoading) {
                  return;
                }
                setDeleteLoading(true);
                await handleRemove(record);
                setDeleteLoading(false);
                setLine(-1);
              }}
              okText="确认删除"
              onCancel={() => {
                setDeleteVisible(false);
                setLine(-1);
              }}
              visible={deleteVisible && line === index}
              okButtonProps={{
                loading: deleteLoading
              }}
              cancelText="再想想">
              <a onClick={() => {
                setDeleteVisible(true);
                setLine(index);
              }}>删除</a>
            </Popconfirm>
          </PermissionControl>
          
        ]
      }
    }
  ];
  const [editOrder, setEditOrder] = useState(false);

  /**
   * 调整栏位排序
   */
  const adjustOrder = async () => {
    navbarList.forEach(item => {
      actionRef.current?.startEditable(item.navbar_id as React.Key);
    });
    
    let editData = navbarList.slice(0);
    if (!editOrder) {
      editData = editData.map(item => {
        item.eidtable = true;
        return item;
      })
      setEditOrder(true);
    } else {
      editData = editData.map(item => {
        item.eidtable = false;
        return item;
      });
      const navbar_list = navbarList.map((item) => {
        return {
          navbar_id: item.navbar_id,
          sort: Number(item.sort)
        }
      });

      try {
        await adjustNavSort({navbar_list});
        showMsg('已保存', MsgType.SUCCESS);
        actionRef.current?.reload()
        navbarList.forEach(item => {
          actionRef.current?.cancelEditable(item.navbar_id as React.Key);
        });
        setEditOrder(false);
      } catch (error) {
        showMsg(error?.data?.errmsg);
      }
    }
    
  }

  /**
   * 添加栏位
   * @param data 
   * @returns 
   */
  const handleAdd = async (data: MALLAPI.NavbarItem) => {
    try {
      const isUpdate = !!data.navbar_id;
      await postNavbar(data, isUpdate);
      showMsg('已保存', MsgType.SUCCESS);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  /**
   * 删除栏位
   * @param record 
   */
  const handleRemove = async (record: MALLAPI.NavbarItem) => {
    try {
      await deleteNavbar(record.navbar_id);
      showMsg('已删除', MsgType.SUCCESS);
      actionRef.current?.reload();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  return (
    <PageContainer extra={[
     ]} breadcrumb={{}}>
      <EditableProTable<MALLAPI.NavbarItem, COMMON.PageParams>
        rowKey="navbar_id"
        bordered
        actionRef={actionRef}
        search={false}
        options={false}
        className='nav-table'
        request={async (param) => {
          try {
            const data: MALLAPI.NavbarItemList = await getNavbarList();
            console.log(data);
            const list = data.record_list.map(item => {
              return {
                ...item,
                navbar_url: replaceImgHost(item.navbar_url || '')
              }
            })
            setNavbarList(list)
            return {
              data: list,
              success: true,
              total: list?.length
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            }
          }
        }}
        pagination={false}
        toolBarRender={() => [
          <div>
            <PermissionControl action_id="500501001">
              <Button 
                onClick={() => {
                  if (navbarList.length >= 10) {
                    return;
                  }
                  setVisible(true);
                  setCurrentRow({});
                  setOptType(OptType.ADD);
                }} 
                disabled={navbarList.length >= 10}
                icon={<PlusOutlined />}
                type="primary">
                新增
              </Button>
            </PermissionControl>
              
            <PermissionControl action_id="500501002">
              <Button 
                style={{marginLeft: 10}}
                onClick={adjustOrder} 
                icon={<SortDescendingOutlined />}
                type="primary">
                {editOrder ? '保存排序' : '调整排序'}
              </Button>
            </PermissionControl>  
            <div>
            <TableHint text="导航栏支持创建至多10个商品栏位。" />
            </div>
          </div>,
        ]}
        editable={{
          type: 'multiple',
          actionRender: () => {
            return [];
          },
          onValuesChange: (record, recordList) => {
            setNavbarList(recordList);
          }
        }}
        columns={columns}
        recordCreatorProps={false}
      />

      {visible && <OptForm 
        handleAdd={handleAdd}
        optType={optType}
        handleModalVisible={setVisible}
        record={currentRow}
        actionRef={actionRef}
      />}
    </PageContainer>
  );
};
export default Index;
